<?php

/**
 * Class TyqLib_Cpas2_Aes 提供aes-128-cbc加密功能
 * php > 5.3
 */

class Lib_Aes {

    private $key = null;
    private $iv = null;

    public function __construct($key)
    {
        if(strlen($key) < 32){
            $key = str_pad($key, 32, '0');
        }
        $this->key = substr($key, 0, 16);
        $this->iv = substr($key, 16, 16);
    }

    /**
     * aes-128-cbc加密
     *
     * @param string $data 需要加密的数据
     * @return 加密后的数据
     */
    public function encrypt($data) {

        $encryptedData = openssl_encrypt($data, 'aes-128-cbc', $this->key, OPENSSL_RAW_DATA, $this->iv);
        $base64en_encryptedData = base64_encode($encryptedData);
        return $base64en_encryptedData;
    }

    /**
     * aes-128-cbc解密
     *
     * @param string $data 需要解密的数据
     * @return 解密后的数据
     */
    public function decrypt($data) {
        $base64de_encryptedData = base64_decode($data);
        $decryptedData = openssl_decrypt($base64de_encryptedData, 'aes-128-cbc', $this->key, OPENSSL_RAW_DATA, $this->iv);
        return $decryptedData;
    }
}
//$ts = '1515383533';
//$key = md5('fsddsfdsf' . $ts);
//$aescipher = new Aes($key);
//
//$data= [
//	"api"=> "pinganPush",
//	"body"=> "json, 请求数据，具体参考接口定义章节"
//];
//$en = $aescipher->encrypt(json_encode($data));
//var_dump($en);
//$de = $aescipher->decrypt($en);
//var_dump($de);